package com.lpf.mybatis.session;

import com.lpf.mybatis.executor.Executor;
import com.lpf.mybatis.config.Configuration;
import com.lpf.mybatis.config.MapperRegistry;
import com.lpf.mybatis.mapper.MapperProxy;

import java.lang.reflect.Proxy;

@SuppressWarnings("all")
public class SqlSession {

    private Configuration configuration;
    private Executor executor;

    public Configuration getConfiguration() {
        return configuration;
    }

    /**
     * 功能描述：关联起来
     */
    public SqlSession(Configuration configuration, Executor executor) {
        this.configuration = configuration;
        this.executor = executor;
    }

    /**
     * 功能描述：返回代理对象
     */
    public <T> T getMapper(Class<T> clazz) {
        return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, new MapperProxy(this, clazz));
    }

    /**
     * 功能描述：执行查询
     *
     * @param mapperData 根据 statementId 在 MapperRegistry 中找到的配置信息（sql、实体类型等）
     * @param parameter  设置到 sql 语句中的数据
     * @return T
     */
    public <T> T selectOne(MapperRegistry.MapperData mapperData, Object parameter) throws Exception {
        return executor.query(mapperData, parameter);
    }
}
